﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain.RBAC;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyWrite.API.Appicant.Command.Users;
using MediatR;

namespace B.S.DataBase.MyWrite.API.Appicant.CommandHandler.Users
{
    public class AddUserCommandHandler : IRequestHandler<AddUserCommand, APIResult<object>>
    {
        private readonly IBaseRepository<User> userrReppos;
        private readonly IMapper mapper;

        public AddUserCommandHandler(IBaseRepository<User> userrReppos, IMapper mapper)
        {
            this.userrReppos = userrReppos;
            this.mapper = mapper;
        }

        public  Task<APIResult<object>> Handle(AddUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = APIEnum.添加成功;
            result.Msg = APIEnum.添加成功.ToString();
            var model = mapper.Map<User>(request);

            var r =userrReppos.GetAll().Result.Where(x=>x.UserName ==request.UserName).FirstOrDefault();
            if(r != null)
            {
                result.Code = APIEnum.添加失败;
                result.Msg = "用户名已存在了".ToString();
                return  Task.FromResult(result);
            }
            var obj = userrReppos.Add(model);


            result.data = obj;
            return  Task.FromResult(result);
        }

    }
}
